using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Samples.SsbTransportChannel;
using System.Transactions;
using System.ServiceModel;
using System.Data.SqlClient;

namespace SsbTransportTestSuite.Services
{
    class TestTransactionEnlistingService : IOrderProcessing
    {
        #region IOrderProcessing Members

        public void BeginOrder(Order order)
        {
            Console.WriteLine("BeginOrder called");
            // save order to database
            SsbConversationGroupReceiver receiver = OperationContext.Current.Channel.GetProperty<SsbConversationGroupReceiver>();
            using (TransactionScope scope = new TransactionScope(receiver.GetTransaction()))
            {
                Transaction.Current.TransactionCompleted += delegate(object tsCompletedSender, TransactionEventArgs tsCompletedArgs)
                {
                    Console.WriteLine("Transaction Completed {0}", tsCompletedArgs.Transaction.TransactionInformation.Status);
                };
                DBUtils.AddServiceOrder(receiver.GetConnection(), receiver.ConversationGroupId, order);
                scope.Complete();
            }
        }

        public void AddOrderItem(OrderItem item)
        {
            Console.WriteLine("AddOrderItem called");
            // add order to database
            SsbConversationGroupReceiver receiver = OperationContext.Current.Channel.GetProperty<SsbConversationGroupReceiver>();
            using (TransactionScope scope = new TransactionScope(receiver.GetTransaction()))
            {
                DBUtils.AddServiceOrderItem(receiver.GetConnection(), receiver.ConversationGroupId, item);
                scope.Complete();
            }
        }

        public void EndOrder()
        {
            Console.WriteLine("EndOrder called");
            // update order status and send confirmation
            SsbConversationGroupReceiver receiver = OperationContext.Current.Channel.GetProperty<SsbConversationGroupReceiver>();
            SqlConnection cn=receiver.GetConnection();
            Guid cgid=receiver.ConversationGroupId;
            using (TransactionScope scope = new TransactionScope(receiver.GetTransaction()))
            {
                IOrderNotification client = receiver.GetCallback<IOrderNotification>();
                DBUtils.UpdateServiceOrder(cn, cgid, OrderStatus.Confirmed);
                client.ConfirmOrder();
                DBUtils.UpdateServiceOrder(cn, cgid, OrderStatus.Prepared);
                client.UpdateOrderStatus(OrderStatus.Prepared);
                DBUtils.UpdateServiceOrder(cn, cgid, OrderStatus.Shipped);
                client.UpdateOrderStatus(OrderStatus.Shipped);
                scope.Complete();
            }
        }

        #endregion
    }
}
